# _*_ coding: utf-8 _*_
from odoo import models, fields, api
from odoo.exceptions import ValidationError


class StockPutOnShelfSplit(models.TransientModel):
    _name = "stock_put_on_shelf.split"

    shelf_line_id = fields.Many2one("stock.put.on.shelf.line")
    qty_available = fields.Float(u"总可用数量", readonly=True)
    line_ids = fields.One2many("stock_put_on_shelf.split.line", "wizard_id")

    @api.constrains("line_ids")
    def _check_lines(self):
        for split in self:
            if sum(l.quantity for l in split.line_ids) > split.qty_available:
                raise ValidationError(u"拆分的明细行的数量累计不能大于总可用数量!")

    def action_ok(self):
        record = self.shelf_line_id
        order = record.shelf_id
        vals = [(2, record.id)]
        for line in self.line_ids:
            vals.append((0, 0, {
                "product_id": record.product_id.id,
                "lot_id": record.lot_id.id,
                "src_location_id": record.src_location_id.id,
                "dest_location_id": line.location_id.id,
                "product_qty": line.quantity,
            }))
        order.write({"line_ids": vals})
        return {'type': 'ir.actions.act_window_close'}


class StockPutOnShelfSplitLine(models.TransientModel):
    _name = "stock_put_on_shelf.split.line"

    wizard_id = fields.Many2one("stock_put_on_shelf.split")
    location_id = fields.Many2one("stock.location", string=u"库位", domain=[('usage', '=', "internal")],
                                  required=True)
    quantity = fields.Float(string=u"数量")
